<template>
  <XenFormPopup
    ref="popupRef"
    :title="dynamicTitle"
    :subtitle="dynamicSubtitle"
    :confirm-text="dynamicConfirmText"
    :loading-text="dynamicLoadingText"
    :loading="loading"
    @confirm="handleConfirm"
    @close="handleClose"
  >
    <template #form>
      <uni-forms ref="formRef" :model="formData" :rules="formRules">
        <!-- 动态渲染表单区块 -->
        <view
          v-for="section in config.sections"
          :key="section.key"
          class="form-section"
        >
          <view class="section-header">
            <view class="section-icon">
              <uni-icons
                :type="section.icon"
                size="20"
                color="#ffffff"
              ></uni-icons>
            </view>
            <view class="section-title">
              <text class="title">{{ section.title }}</text>
              <text class="subtitle">{{ section.subtitle }}</text>
            </view>
          </view>

          <view class="section-content">
            <!-- 动态渲染字段行 -->
            <view
              v-for="row in section.rows"
              :key="row.key"
              class="input-row"
              :class="{ single: row.fields.length === 1 }"
            >
              <!-- 动态渲染字段 -->
              <view
                v-for="field in row.fields"
                :key="field.key"
                class="input-group"
              >
                <view class="input-label">
                  <uni-icons
                    :type="field.icon"
                    size="18"
                    color="#14b8a6"
                  ></uni-icons>
                  <text class="label-text">
                    {{ field.label }}
                    <text v-if="field.required" class="required">*</text>
                  </text>
                </view>

                <!-- 文本输入框 -->
                <uni-forms-item v-if="field.type === 'input'" :name="field.key">
                  <uni-easyinput
                    v-model="formData[field.key]"
                    :placeholder="field.placeholder"
                    :type="field.inputType || 'text'"
                    :maxlength="field.maxlength"
                    :clearable="false"
                    class="custom-input"
                  />
                </uni-forms-item>

                <!-- 文本域 -->
                <uni-forms-item
                  v-else-if="field.type === 'textarea'"
                  :name="field.key"
                >
                  <uni-easyinput
                    v-model="formData[field.key]"
                    :placeholder="field.placeholder"
                    type="textarea"
                    :autoHeight="true"
                    :maxlength="field.maxlength || 500"
                    :clearable="false"
                    class="custom-textarea"
                  />
                </uni-forms-item>

                <!-- 普通Picker选择器 - APP端使用专用组件 -->
                <!-- #ifdef APP-PLUS -->
                <uni-forms-item
                  v-else-if="field.type === 'picker'"
                  :name="field.key"
                >
                  <XenAppSelector
                    :model-value="formData[field.key]"
                    :options="getPickerRange(field)"
                    :placeholder="field.placeholder"
                    :option-text-field="field.rangeKey || 'text'"
                    :option-value-field="'value'"
                    @update:model-value="
                      (value) => handleAppSelectorChange(field.key, value)
                    "
                  />
                </uni-forms-item>
                <!-- #endif -->

                <!-- 普通Picker选择器 - 其他平台使用原生picker -->
                <!-- #ifndef APP-PLUS -->
                <uni-forms-item
                  v-else-if="field.type === 'picker'"
                  :name="field.key"
                >
                  <picker
                    class="custom-picker"
                    mode="selector"
                    :range="getPickerRange(field)"
                    :range-key="field.rangeKey || 'text'"
                    :value="getPickerIndex(field.key, field)"
                    @change="
                      (e: any) => handlePickerChange(field.key, field, e)
                    "
                  >
                    <view class="picker-content">
                      <text
                        class="picker-text"
                        :class="{
                          'has-value': getPickerDisplayText(field.key, field),
                        }"
                        >{{
                          getPickerDisplayText(field.key, field) ||
                          field.placeholder
                        }}</text
                      >
                      <uni-icons type="down" size="16" color="#999"></uni-icons>
                    </view>
                  </picker>
                </uni-forms-item>
                <!-- #endif -->

                <!-- 日期选择器 - APP端使用专用组件 -->
                <!-- #ifdef APP-PLUS -->
                <uni-forms-item
                  v-else-if="field.type === 'date'"
                  :name="field.key"
                >
                  <XenAppDatePicker
                    :model-value="formData[field.key]"
                    :placeholder="field.placeholder"
                    @update:model-value="
                      (value) => handleAppDateChange(field.key, value)
                    "
                  />
                </uni-forms-item>
                <!-- #endif -->

                <!-- 日期选择器 - 其他平台使用原生picker -->
                <!-- #ifndef APP-PLUS -->
                <uni-forms-item
                  v-else-if="field.type === 'date'"
                  :name="field.key"
                >
                  <picker
                    class="custom-picker"
                    mode="date"
                    :value="formData[field.key]"
                    @change="(e: any) => handleDateChange(field.key, e)"
                  >
                    <view class="picker-content">
                      <text
                        class="picker-text"
                        :class="{ 'has-value': formData[field.key] }"
                        >{{ formData[field.key] || field.placeholder }}</text
                      >
                      <uni-icons type="down" size="16" color="#999"></uni-icons>
                    </view>
                  </picker>
                </uni-forms-item>
                <!-- #endif -->

                <!-- 文件上传 -->
                <view
                  v-else-if="field.type === 'file'"
                  class="file-upload-container"
                >
                  <uni-file-picker
                    v-model="fileValues[field.key]"
                    fileMediatype="all"
                    mode="list"
                    limit="1"
                    :title="field.placeholder"
                    :delIcon="true"
                    @select="(e) => selectFile(field.key, e)"
                    @success="(e) => uploadFileSuccess(field.key, e)"
                    @fail="(e) => uploadFileFail(field.key, e)"
                    @delete="(e) => deleteFile(field.key, e)"
                  ></uni-file-picker>

                  <view class="upload-tips">
                    <text>{{ field.tips || "支持Word、PDF、图片格式" }}</text>
                  </view>
                </view>

                <!-- 多文件上传 -->
                <view
                  v-else-if="field.type === 'multifile'"
                  class="file-upload-container"
                >
                  <uni-file-picker
                    v-model="fileValues[field.key]"
                    fileMediatype="all"
                    mode="list"
                    limit="9"
                    :title="field.placeholder"
                    :delIcon="true"
                    @select="(e) => selectMultiFile(field.key, e)"
                    @success="(e) => uploadMultiFileSuccess(field.key, e)"
                    @fail="(e) => uploadMultiFileFail(field.key, e)"
                    @delete="(e) => deleteMultiFile(field.key, e)"
                  ></uni-file-picker>

                  <view class="upload-tips">
                    <text>{{
                      field.tips || "支持Word、PDF、图片格式，可上传多个文件"
                    }}</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </uni-forms>
    </template>
  </XenFormPopup>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, nextTick } from "vue";
import XenFormPopup from "@/components/XenFormPopup.vue";
import { uploadImage } from "@/utils/unirequest";
import type {
  FieldConfig,
  PopupConfig,
} from "@/subpkg-hr-syshrinterviewrequestbill/components/popupConfigs";
// #ifdef APP-PLUS
import XenAppSelector from "@/components/XenAppSelector.vue";
import XenAppDatePicker from "@/components/XenAppDatePicker.vue";
// #endif

// Props
interface Props {
  show: boolean;
  config: PopupConfig;
  personId?: string;
  editData?: any;
  onSubmit?: (data: any) => Promise<void>;
}

const props = defineProps<Props>();

// Emits
const emit = defineEmits<{
  "update:show": [value: boolean];
  confirm: [];
}>();

// 弹窗引用
const popupRef = ref();
const formRef = ref();

// 状态管理
const loading = ref(false);
const formData = ref<Record<string, any>>({});
const fileValues = ref<Record<string, any[]>>({});

// 动态标题和文本（根据是否有编辑数据判断是新增还是编辑）
const isEditMode = computed(
  () => props.editData && Object.keys(props.editData).length > 0,
);

const dynamicTitle = computed(() => {
  if (isEditMode.value) {
    return props.config.title.replace("新增", "编辑");
  }
  return props.config.title;
});

const dynamicSubtitle = computed(() => {
  if (isEditMode.value) {
    return props.config.subtitle
      .replace("新增", "编辑")
      .replace("请填写", "请修改");
  }
  return props.config.subtitle;
});

const dynamicConfirmText = computed(() => {
  if (isEditMode.value) {
    return props.config.confirmText
      .replace("新增", "保存")
      .replace("确认新增", "确认保存");
  }
  return props.config.confirmText;
});

const dynamicLoadingText = computed(() => {
  if (isEditMode.value) {
    return props.config.loadingText.replace("新增中", "保存中");
  }
  return props.config.loadingText;
});

// 表单验证规则
const formRules = computed(() => {
  const rules: Record<string, any> = {};

  props.config.sections.forEach((section: any) => {
    section.rows.forEach((row: any) => {
      row.fields.forEach((field: any) => {
        const fieldRules: any[] = [];

        // 必填验证
        if (field.required) {
          fieldRules.push({
            required: true,
            errorMessage: `请${field.type === "picker" ? "选择" : "输入"}${
              field.label
            }`,
          });
        }

        // 正则验证
        if (field.pattern) {
          fieldRules.push({
            pattern: field.pattern,
            errorMessage:
              field.patternErrorMessage || `${field.label}格式不正确`,
          });
        }

        if (fieldRules.length > 0) {
          rules[field.key] = {
            rules: fieldRules,
          };
        }
      });
    });
  });

  return rules;
});

// 初始化表单数据
const initFormData = () => {
  const data: Record<string, any> = {};
  const files: Record<string, any[]> = {};

  props.config.sections.forEach((section: any) => {
    section.rows.forEach((row: any) => {
      row.fields.forEach((field: any) => {
        // 如果有编辑数据，优先使用编辑数据，否则使用默认值
        if (props.editData && props.editData[field.key] !== undefined) {
          let value = props.editData[field.key];

          // 如果是日期类型字段，处理日期格式，去掉时分秒
          if (field.type === "date" && value) {
            // 将日期字符串转换为YYYY-MM-DD格式
            const date = new Date(value);
            if (!isNaN(date.getTime())) {
              value = date.toISOString().split("T")[0];
            }
          }

          data[field.key] = value;
        } else {
          data[field.key] =
            field.defaultValue !== undefined ? field.defaultValue : "";
        }

        if (field.type === "file" || field.type === "multifile") {
          files[field.key] = [];
        }
      });
    });
  });

  formData.value = data;
  fileValues.value = files;
};

// 日期选择处理
const handleDateChange = (fieldKey: string, e: any) => {
  formData.value[fieldKey] = e.detail.value;
};

// 获取picker的选项数组
const getPickerRange = (field: FieldConfig) => {
  return field.options || [];
};

// 获取picker当前选中的索引
const getPickerIndex = (fieldKey: string, field: FieldConfig) => {
  const currentValue = formData.value[fieldKey];
  if (!currentValue) return 0;

  const options = field.options || [];
  const index = options.findIndex(
    (option: any) => option.value === currentValue,
  );
  return index >= 0 ? index : 0;
};

// 获取picker显示的文本
const getPickerDisplayText = (fieldKey: string, field: FieldConfig) => {
  const currentValue = formData.value[fieldKey];
  if (!currentValue) return "";

  const options = field.options || [];
  const option = options.find((option: any) => option.value === currentValue);
  return option ? option.text : "";
};

// picker选择处理
const handlePickerChange = (fieldKey: string, field: FieldConfig, e: any) => {
  const index = e.detail.value;
  const options = field.options || [];

  if (options && options[index]) {
    formData.value[fieldKey] = options[index].value;
  }
};

// APP端选择器变化处理
const handleAppSelectorChange = (fieldKey: string, value: any) => {
  formData.value[fieldKey] = value;
};

// APP端日期选择处理
const handleAppDateChange = (fieldKey: string, value: any) => {
  formData.value[fieldKey] = value;
};

// 获取文件URL
const getFileUrl = (fileId: string | null) => {
  if (!fileId) return "";
  return `${import.meta.env.VITE_BASE_URL}/api/_file/getfile/${fileId}`;
};

// 文件选择处理
const selectFile = async (fieldKey: string, e: any) => {
  console.log(`选择${fieldKey}文件：`, e);
  const file = e.tempFiles?.[0] || e.tempFiles;
  const filePath = file?.path || file?.tempFilePath;

  if (filePath) {
    try {
      const fileId = await uploadImage(filePath, "file");
      console.log(`${fieldKey}上传成功，文件ID:`, fileId);
      formData.value[fieldKey] = fileId;

      // 更新file-picker显示的数据
      const fileName = file?.name || file?.fileName || "文件";
      fileValues.value[fieldKey] = [
        {
          name: fileName,
          url: getFileUrl(fileId),
          extname: file?.extname || "pdf",
          size: file?.size || 0,
          fileID: fileId,
        },
      ];
    } catch (error) {
      console.error(`${fieldKey}上传失败:`, error);
      uni.showToast({
        title: "文件上传失败，请重试",
        icon: "none",
      });
    }
  }
};

// 文件上传成功回调
const uploadFileSuccess = (fieldKey: string, e: any) => {
  console.log(`${fieldKey}上传成功：`, e);
};

// 文件上传失败回调
const uploadFileFail = (fieldKey: string, e: any) => {
  console.log(`${fieldKey}上传失败：`, e);
  uni.showToast({
    title: "文件上传失败，请重试",
    icon: "none",
  });
};

// 删除文件
const deleteFile = (fieldKey: string, e: any) => {
  console.log(`删除${fieldKey}：`, e);
  formData.value[fieldKey] = "";
  fileValues.value[fieldKey] = [];
};

// 获取多文件ID数组
const getFileIds = (fieldKey: string): string[] => {
  const fileIdsStr = formData.value[fieldKey];
  if (!fileIdsStr) return [];
  return fileIdsStr.split(",").filter((id: string) => id.trim());
};

// 多文件选择处理
const selectMultiFile = async (fieldKey: string, e: any) => {
  console.log(`选择${fieldKey}多文件：`, e);
  const files = e.tempFiles || [];

  if (files.length === 0) return;

  try {
    const uploadPromises = files.map(async (file: any) => {
      const filePath = file?.path || file?.tempFilePath;
      if (filePath) {
        const fileId = await uploadImage(filePath, "file");
        console.log(`${fieldKey}文件上传成功，文件ID:`, fileId);
        return {
          fileId,
          name: file?.name || file?.fileName || "文件",
          extname: file?.extname || "pdf",
          size: file?.size || 0,
        };
      }
      return null;
    });

    const uploadResults = await Promise.all(uploadPromises);
    const validResults = uploadResults.filter((result) => result !== null);

    if (validResults.length > 0) {
      // 获取现有的文件ID
      const existingIds = getFileIds(fieldKey);
      const newIds = validResults.map((result) => result!.fileId);
      const allIds = [...existingIds, ...newIds];

      // 更新表单数据
      formData.value[fieldKey] = allIds.join(",");

      // 更新file-picker显示的数据
      const existingFiles = fileValues.value[fieldKey] || [];
      const newFiles = validResults.map((result) => ({
        name: result!.name,
        url: getFileUrl(result!.fileId),
        extname: result!.extname,
        size: result!.size,
        fileID: result!.fileId,
      }));

      fileValues.value[fieldKey] = [...existingFiles, ...newFiles];
    }
  } catch (error) {
    console.error(`${fieldKey}多文件上传失败:`, error);
    uni.showToast({
      title: "文件上传失败，请重试",
      icon: "none",
    });
  }
};

// 多文件上传成功回调
const uploadMultiFileSuccess = (fieldKey: string, e: any) => {
  console.log(`${fieldKey}多文件上传成功：`, e);
};

// 多文件上传失败回调
const uploadMultiFileFail = (fieldKey: string, e: any) => {
  console.log(`${fieldKey}多文件上传失败：`, e);
  uni.showToast({
    title: "文件上传失败，请重试",
    icon: "none",
  });
};

// 删除多文件
const deleteMultiFile = (fieldKey: string, e: any) => {
  console.log(`删除${fieldKey}多文件：`, e);
  const deleteIndex = e.index;

  // 更新fileValues
  const currentFiles = fileValues.value[fieldKey] || [];
  currentFiles.splice(deleteIndex, 1);
  fileValues.value[fieldKey] = currentFiles;

  // 更新formData中的文件ID字符串
  const fileIds = currentFiles
    .map((file: any) => file.fileID)
    .filter((id: string) => id);
  formData.value[fieldKey] = fileIds.join(",");
};

// 重置表单
const resetForm = () => {
  initFormData();
  if (formRef.value) {
    formRef.value.clearValidate();
  }
};

// 处理关闭
const handleClose = () => {
  emit("update:show", false);
  resetForm();
};

// 处理确认
const handleConfirm = async () => {
  try {
    // 表单验证
    const valid = await formRef.value.validate();
    if (!valid) return;

    loading.value = true;

    // 处理表单数据
    const submitData = { ...formData.value };

    console.log("提交的数据:", submitData);

    // 如果有自定义提交函数，使用自定义函数
    if (props.onSubmit) {
      await props.onSubmit(submitData);
    }

    uni.showToast({
      title: "操作成功",
      icon: "success",
    });

    emit("confirm");
    handleClose();
  } finally {
    loading.value = false;
  }
};

// 监听显示状态
watch(
  () => props.show,
  (newVal) => {
    if (newVal) {
      nextTick(() => {
        popupRef.value?.open();
      });
      initFormData(); // 重新初始化表单数据，包含编辑数据
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    } else {
      popupRef.value?.close();
    }
  },
  { immediate: true },
);

// 监听编辑数据变化
watch(
  () => props.editData,
  () => {
    if (props.show) {
      initFormData(); // 编辑数据变化时重新初始化表单
    }
  },
  { deep: true },
);

// 组件挂载
onMounted(() => {
  initFormData();
});
</script>

<style lang="scss" scoped>
.form-section {
  margin-bottom: 32rpx;
  border-radius: 16rpx;
  background: #ffffff;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);

  .section-header {
    display: flex;
    align-items: center;
    padding: 24rpx 32rpx;
    background: linear-gradient(135deg, #14b8a6 0%, #0891b2 100%);
    position: relative;

    &::after {
      content: "";
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      height: 1rpx;
      background: rgba(255, 255, 255, 0.2);
    }

    .section-icon {
      width: 56rpx;
      height: 56rpx;
      border-radius: 50%;
      background: rgba(255, 255, 255, 0.2);
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 20rpx;
    }

    .section-title {
      flex: 1;

      .title {
        display: block;
        font-size: 32rpx;
        font-weight: 600;
        color: #ffffff;
        line-height: 1.4;
      }

      .subtitle {
        display: block;
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.8);
        margin-top: 4rpx;
        line-height: 1.3;
      }
    }
  }

  .section-content {
    padding: 32rpx;
  }
}

.input-row {
  display: flex;
  gap: 24rpx;
  margin-bottom: 24rpx;

  &:last-child {
    margin-bottom: 0;
  }

  &.single {
    .input-group {
      flex: 1;
    }
  }

  .input-group {
    flex: 1;
    min-width: 0;

    .input-label {
      display: flex;
      align-items: center;
      margin-bottom: 12rpx;

      .label-text {
        font-size: 28rpx;
        color: #2c3e50;
        font-weight: 500;
        margin-left: 8rpx;

        .required {
          color: #ef4444;
        }
      }
    }

    .custom-input,
    .custom-picker,
    .custom-textarea {
      border: 1px solid #dcdfe6;
      transition: all 0.3s ease;
      background: #ffffff;

      &:focus,
      &:focus-within {
        border-color: #14b8a6;
        box-shadow: 0 0 0 4rpx rgba(20, 184, 166, 0.1);
      }
    }

    .custom-picker {
      .picker-content {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0px 10px;
        min-height: 35px;
        background: #ffffff;

        .picker-text {
          font-size: 12px;
          color: #9ca3af;
          flex: 1;

          &.has-value {
            font-size: 14px !important;
            color: #000000 !important;
          }
        }
      }
    }

    .custom-textarea {
      min-height: 120rpx;
    }

    .file-upload-container {
      margin-top: 12rpx;

      .upload-tips {
        margin-top: 8rpx;
        padding: 8rpx 12rpx;
        background: #f8fafc;
        border-radius: 6rpx;
        border-left: 3rpx solid #14b8a6;

        text {
          font-size: 20rpx;
          color: #6b7280;
          display: block;
          line-height: 1.4;
        }
      }
    }
  }
}

// 强制修改uni-easyinput的样式
:deep(.uni-easyinput) {
  .is-input-border {
    border: none !important;
    border-radius: 0 !important;
  }
}

// 响应式处理
@media (max-width: 750rpx) {
  .input-row {
    flex-direction: column;
    gap: 0;

    .input-group {
      margin-bottom: 24rpx;

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}
</style>
